import React, { useEffect, useMemo, useState } from 'react';
import TreeList from '../Permission/Tree';
import Permission from '../Permission';
import '../../../style.less';
import { Empty, Spin } from 'antd';
import { getModule, getModel, getModelPerm } from '../../../service';
import { getMessage, TextWidget } from '@inbiz/react';
const action = {
  Name: getMessage('Permission.action'),
  key: 'action',
  selectable: false,
  children: [
    {
      Name: getMessage('Permission.view'),
      key: 'select&1',
      isLeaf: true,
    },
    {
      Name: getMessage('Permission.add'),
      key: 'add&1',
      isLeaf: true,
    },
    {
      Name: getMessage('Permission.edit'),
      key: 'edit&1',
      isLeaf: true,
    },
    {
      Name: getMessage('Permission.delete'),
      key: 'delete&1',
      isLeaf: true,
    },
  ],
};

function Model(props) {
  const { permConfig, appId, containerHeight } = props;
  const [modelData, $modelData] = useState([]); //模型数据
  const [selectModel, $selectModel] = useState([]); // 选中模型
  const [modelFields, $modelFields] = useState([]); //动作和属性
  const [selectFields, $selectFields] = useState([]); // 选中动作或属性
  const [permList, $permList] = useState([]); //权限列表
  const [loadding1, $loadding1] = useState(false);

  //获取模型分组
  useEffect(() => {
    getModuleList();
  }, []);

  //获取动作或属性
  useEffect(() => {
    $modelFields([]);
    if (selectModel.length) {
      $modelFields((oringe) => {
        return getModelFields(selectModel);
      });
    }
  }, [selectModel]);

  //获取动作或属性的权限列表
  useEffect(() => {
    $permList([]);
    if (selectFields.length) {
      getPermList();
    }
  }, [selectFields]);

  // 获取当前站点下的模型分组
  const getModuleList = () => {
    $loadding1(true);
    getModule({
      appId,
    }).then((res) => {
      $loadding1(false);
      $modelData(formatData(res.List));
    });
  };

  //moduleList数据格式化处理
  const formatData = (list, child?, key?) => {
    //child:true为子级
    if (list?.length) {
      list = list.map((item) => {
        let parm = {
          ...item,
          key: key ? `${item[key]}&0` : item.Key || item.ModelKey,
          isLeaf: child ? true : false,
          selectable: child ? true : false,
        };
        return parm;
      });
      return list;
    } else {
      return [];
    }
  };

  // 异步加载菜单
  const onLoadData = (treeNode) => {
    return new Promise<void>((resolve) => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      getModel({ moduleId: treeNode.props.dataRef.ID }).then((res) => {
        if (res) {
          const data = formatData(res.List, true).filter((item) => {
            return item.PublishState == 1;
          });
          treeNode.props.dataRef.children = data;
          $modelData(updateTreeData(modelData, data, treeNode.props.eventKey));
          resolve();
        }
      });
    });
  };

  const updateTreeData = (list, children, key) => {
    return list.map((node) => {
      if (node.key === key) {
        return {
          ...node,
          children,
        };
      }
      if (node.children) {
        return {
          ...node,
          children: updateTreeData(node.children, key, children),
        };
      }
      return node;
    });
  };

  // 根据选中模型获取模型字段
  const getModelFields = (modelkey) => {
    let list = [];
    modelData?.map((item) => {
      if (item.children?.length) {
        item.children.map((item1) => {
          if (item1.ModelKey == modelkey[0]) {
            list = item1.Fields;
          }
        });
      }
    });
    // 获取已发布的模型字段
    list = formatData(list, true, 'Name').filter((item) => {
      return item.PublishState == 1;
    });
    return [
      action,
      // {
      //   Name: '属性',
      //   key: 'fields',
      //   selectable: false,
      //   children: list,
      // }
    ];
  };

  //获取权限列表
  const getPermList = (search?) => {
    let parm = {
      fieldName: selectFields[0].split('&')[0],
      type: selectFields[0].split('&')[1],
      searchText: search,
      modelKey: selectModel[0],
    };
    getModelPerm(parm).then((res) => {
      if (res) {
        $permList((oringe) => {
          return res;
        });
      }
    });
  };
  // 判断是否是ifream嵌套
  const isIfream = useMemo(() => {
    return location?.hash?.indexOf('permissionFun') != -1;
  }, []);

  return (
    <div
      className={'main'}
      style={{ height: `calc(${containerHeight} - 144px)` }}
    >
      <div
        className={'treeList'}
        style={{
          borderLeft: '1px solid #eee',
          width: '180px',
          flex: '0 0 180px',
        }}
      >
        {modelData.length ? (
          <TreeList
            key={appId}
            list={modelData}
            onLoadData={onLoadData}
            selectedKeys={selectModel}
            treeClick={(arr) => $selectModel(arr)}
          />
        ) : loadding1 ? (
          <Spin className={'spindiv'} />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>
      <div className={'treeList'}>
        {modelFields.length ? (
          <TreeList
            key={selectModel}
            list={modelFields}
            selectedKeys={selectFields}
            treeClick={(arr) => $selectFields(arr)}
          />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>

      <div className={`${isIfream ? 'iframePerm' : 'permission'}`}>
        <Permission
          outId={selectModel[0]}
          menuId={selectFields[0]}
          key={selectFields[0] || 'model'}
          list={permList}
          onRefresh={getPermList}
          permtype={'model'}
          permConfig={permConfig}
        />
      </div>
    </div>
  );
}

export default Model;
export { action };
